package com.tennis.tennisreservation.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信服务类，用于处理微信相关API
 */
@Service
public class WxService {

    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.secret}")
    private String secret;

    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 获取微信access_token
     * @return access_token
     */
    public String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
        Map<String, Object> response = restTemplate.getForObject(url, Map.class);
        
        if (response != null && response.containsKey("access_token")) {
            return (String) response.get("access_token");
        }
        
        throw new RuntimeException("获取微信access_token失败: " + (response != null ? response.toString() : "null"));
    }

    /**
     * 通过手机号获取凭证code获取用户手机号
     * 
     * @param code 手机号获取凭证
     * @return 用户手机号信息
     */
    public Map<String, Object> getPhoneNumber(String code) {
        try {
            String accessToken = getAccessToken();
            String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
            
            // 准备请求体，使用JSON格式直接构建
            String requestJson = "{\"code\":\"" + code + "\"}";
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            // 创建请求实体，直接使用String类型的JSON
            HttpEntity<String> requestEntity = new HttpEntity<>(requestJson, headers);
            
            Map<String, Object> response = restTemplate.postForObject(url, requestEntity, Map.class);
            
            if (response != null) {
                // 检查微信API返回的错误码
                if (response.containsKey("errcode") && !response.get("errcode").equals(0)) {
                    throw new RuntimeException("获取手机号失败: " + response.toString());
                }
                
                // 返回手机号信息
                return response;
            }
            
            throw new RuntimeException("获取手机号失败: 请求返回为空");
        } catch (Exception e) {
            System.err.println("获取手机号异常: " + e.getMessage());
            throw new RuntimeException("获取手机号异常: " + e.getMessage());
        }
    }

    /**
     * 解析手机号响应，获取实际手机号
     * @param phoneResponse 微信API返回的手机号响应
     * @return 用户手机号
     */
    public String parsePhoneNumber(Map<String, Object> phoneResponse) {
        // 检查返回结果中是否包含data字段
        if (phoneResponse != null && phoneResponse.containsKey("data")) {
            Map<String, Object> data = (Map<String, Object>) phoneResponse.get("data");
            
            // 检查data中是否包含phone_info
            if (data != null && data.containsKey("phone_info")) {
                Map<String, Object> phoneInfo = (Map<String, Object>) data.get("phone_info");
                
                // 从phone_info中获取手机号
                if (phoneInfo != null && phoneInfo.containsKey("phoneNumber")) {
                    return (String) phoneInfo.get("phoneNumber");
                } else if (phoneInfo != null && phoneInfo.containsKey("purePhoneNumber")) {
                    return (String) phoneInfo.get("purePhoneNumber");
                }
            } else if (data != null && data.containsKey("phoneNumber")) {
                // 直接从data中获取手机号
                return (String) data.get("phoneNumber");
            }
        }
        
        // 按照原来的格式再尝试解析
        if (phoneResponse != null && phoneResponse.containsKey("phone_info")) {
            Map<String, Object> phoneInfo = (Map<String, Object>) phoneResponse.get("phone_info");
            if (phoneInfo != null && phoneInfo.containsKey("phoneNumber")) {
                return (String) phoneInfo.get("phoneNumber");
            } else if (phoneInfo != null && phoneInfo.containsKey("purePhoneNumber")) {
                return (String) phoneInfo.get("purePhoneNumber");
            }
        }
        
        throw new RuntimeException("解析手机号失败: " + (phoneResponse != null ? phoneResponse.toString() : "null"));
    }
    
    /**
     * 通过微信登录临时凭证获取openid
     * @param code 微信登录临时凭证
     * @return 用户openid
     */
    public String getOpenidByCode(String code) {
        try {
            // 微信登录凭证校验接口
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + 
                        "&secret=" + secret + 
                        "&js_code=" + code + 
                        "&grant_type=authorization_code";
            
            // 直接使用简单的方式请求字符串响应
            String responseStr = new org.springframework.web.client.RestTemplate().getForObject(url, String.class);
            System.out.println("微信API原始响应: " + responseStr);
            
            if (responseStr == null || responseStr.isEmpty()) {
                throw new RuntimeException("微信API返回为空");
            }
            
            // 手动解析JSON字符串
            com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
            com.fasterxml.jackson.databind.JsonNode rootNode = mapper.readTree(responseStr);
            
            // 检查errcode字段
            if (rootNode.has("errcode") && rootNode.get("errcode").asInt() != 0) {
                // 某些情况下返回errcode=0也是正常的，需要验证
                int errcode = rootNode.get("errcode").asInt();
                if (errcode != 0) {
                    String errmsg = rootNode.has("errmsg") ? rootNode.get("errmsg").asText() : "未知错误";
                    throw new RuntimeException("微信API返回错误: " + errcode + " - " + errmsg);
                }
            }
            
            // 提取openid
            if (rootNode.has("openid")) {
                String openid = rootNode.get("openid").asText();
                System.out.println("成功获取openid: " + openid);
                return openid;
            } else {
                System.out.println("微信API响应中未找到openid: " + responseStr);
                throw new RuntimeException("微信API响应中未找到openid");
            }
        } catch (Exception e) {
            System.err.println("获取openid异常: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("获取openid异常: " + e.getMessage(), e);
        }
    }
} 